package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserLoginMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class ApUserLoginServiceImpl extends ServiceImpl<ApUserLoginMapper, ApUser> implements ApUserLoginService {
    /**
     * app端用户登录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        //参数校验
        if (dto == null || StringUtils.isBlank(dto.getEquipmentId())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //输入手机密码登录
        if (StringUtils.isNotBlank(dto.getPassword()) && StringUtils.isNotBlank(dto.getPhone())) {
            //查询用户是否存在
            LambdaQueryWrapper<ApUser> wrapper = Wrappers.<ApUser>lambdaQuery()
                    .eq(ApUser::getPhone, dto.getPhone())
                    .eq(ApUser::getStatus, 0);
            ApUser apUser = getOne(wrapper);
            if (apUser == null) {
                CustException.cust("账号密码错误,请重新登录");
            }
            //校验密码正确与否
            String salt = apUser.getSalt();
            String pwd = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());
            String dbpwd = apUser.getPassword();
            if (!pwd.equals(dbpwd)) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "账号或者密码错误");
            }
            //生成token
            String token = AppJwtUtil.getToken(apUser.getId().longValue());
            //封装返回(隐私信息设置为空)
            apUser.setSalt(null);
            apUser.setPassword(null);
            Map map = new HashMap();
            map.put("token", token);
            map.put("user", apUser);
            return ResponseResult.okResult(map);
        } else {
            //不登录,先看看
            String token = AppJwtUtil.getToken(0L);
            Map map = new HashMap();
            map.put("token", token);
            return ResponseResult.okResult(map);
        }
    }
}
